<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    李梓钿
 *
 */
 
namespace osc\mobile\controller;
use think\Db;
use think\Session;
use think\File;

class User extends MobileBase
{
	protected function _initialize(){
		parent::_initialize();						
		define('UID',is_login());	
		//手机版
		if(!UID){		
			$this->redirect('login/login');					
		}

		if (!Session::has("username")) {

            $this->redirect('login/login');

        }

		$this->assign('flag','user');
	}

	/**
	 * 个人中心
	 * @return mixed
	 */
	function index(){

		if (!Session::has("username")) {
            $this->redirect('login/login');
        }

        $username = session('username');
        $userinfo = Db::name('member')->where('username',$username)->find();
        $map['state'] = array('lt',2);
        $agent = Db::name('agent')->where('username',$username)->where($map)->find();

        $name="VIP";
       	if($userinfo['user_state'] == 2) {
			$name = "银卡";
		}
		else if($userinfo['user_state'] == 3) {
			$name="金卡";
		}
		else if($userinfo['user_state'] == 4) {
			$name="钻卡";
		}

        if($agent)
        {
        	$name="代理";
        }

		$this->assign('agent',$agent);
		$this->assign('userinfo',$userinfo);
		$this->assign('name',$name);
		$this->assign('top_title','个人中心');
		$this->assign('SEO',['title'=>'个人中心-'.config('SITE_TITLE')]);
		return $this->fetch();
	}

	/**
	 * 会员升级
	 * @return mixed
	 */
	function shengji(){

		$this->assign('top_title','会员升级');
		$this->assign('SEO',['title'=>'会员升级-'.config('SITE_TITLE')]);
		return $this->fetch();
	}

	/**
	 * 会员升级操作
	 * @throws \think\Exception
	 */
	function shengji_sub(){
		$data = $this->request->param('type');

		if(!$data){ $this->error('提交错误，请重新尝试');}

		$user = Db::name('member')->where('uid',UID)->find();
		$card = 0;
		$activation = 0;
		//vip
		if($data == 1){

			if($user['user_state'] > 0) $this->error('您当前已经是此会员等级');

			$card = config('upgrade_vip')*0.3;
			$activation = config('upgrade_vip')*0.7;
		}
		//银卡
		if($data == 2){

			if($user['user_state'] > 1) $this->error('您当前已经是此会员等级');

			$card = config('upgrade_silver')*0.3;
			$activation = config('upgrade_silver')*0.7;
		}
		//金卡
		if($data == 3){
			if($user['user_state'] > 2) $this->error('您当前已经是此会员等级');
			$card = config('upgrade_gold')*0.3;
			$activation = config('upgrade_gold')*0.7;
		}
		//钻卡
		if($data == 4){
			if($user['user_state'] > 3) $this->error('您当前已经是此会员等级');
			$card = config('upgrade_drill')*0.3;
			$activation = config('upgrade_drill')*0.7;
		}

		if($card == 0){
			$this->error('不在购买范围内，请重新购买');
		}

		if($card > $user['card']) $this->error('您当前通证不足');
		if($activation > $user['activation']) $this->error('您当前激活积分不足');

		$map = [
			'uid'		=> UID,
			'type'		=> $data,
			'num'		=> $card+$activation,
			'sub_time'	=> date('Y-m-d H:i:s',time())
		];

		$red = Db::name('upgrade_record')->insert($map);
		$res = Db::name('member')->where('uid',UID)->dec('card',$card)->dec('activation',$activation)->exp('user_state',$data)->update();

		if($res && $red){
			$this->success('升级成功','user/index');
		}
		$this->error('升级失败');
	}

	/**
	 * 我的邀请码
	 * @return mixed
	 */
	function invitation(){
		$user = Db::name('member')->where('uid',UID)->find();
		$this->assign('user',$user);
		$this->assign('top_title','我的邀请码');
		$this->assign('SEO',['title'=>'邀请码-'.config('SITE_TITLE')]);
		return $this->fetch();
	}

	function substr_cut($user_name)
	{
	    $strlen     = mb_strlen($user_name, 'utf-8');
	    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
	    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
	    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
	}
	
	function order_count($status){		
		return count(Db::name('order')->where(array('order_status_id'=>$status,'uid'=>UID))->select());		
	}
	
	function wish_list(){
		
		$this->assign('top_title','我的收藏');
		$this->assign('SEO',['title'=>'我的收藏-'.config('SITE_TITLE')]);
		return $this->fetch();
	}
	
	function ajax_wish_list(){
		
    	$page=(int)input('param.page');//页码
		
		$limit = (6 * $page) . ",6";			
			
		$list= Db::view('Goods','goods_id,image,price,name')
		->view('MemberWishlist','uid','Goods.goods_id=MemberWishlist.goods_id')						
		->where(array('MemberWishlist.uid'=>UID))->limit($limit)->select();
		
		if(isset($list)&&is_array($list)){
			foreach ($list as $k => $v) {				
				$list[$k]['image']=resize($v['image'], 200, 200);		
			}				
		}
		
		return $list;
		
	}
	
	function remove_wish(){		
		osc_service('common','member')->remove_wish(input('param.id'),UID);
		storage_user_action(UID,member('nickname'),config('FRONTEND_USER'),'删除了收藏');
		
		$this->redirect('User/wish_list');
	}


	/**
	 * 修改密码
	 * @return array|mixed
	 */
	function updateuserpasswd()
	{
		if(request()->isPost()){
			$data=input('post.');
//			var_dump($data);exit;
			$r=osc_service('common','Member')->updateuserpasswd($data);
			if(isset($r['error'])){
				return $r;
			}	
			return array('success'=>'修改密码成功','url'=>'/mobile');

		}
		
		$this->assign('top_title','修改密码');
		$this->assign('userinfo',Db::name('member')->where('uid',UID)->find());		
		$this->assign('SEO',['title'=>'修改密码-'.config('SITE_TITLE')]);
		
		$this->assign('flag','user');
		
		return $this->fetch();
	}


	/**
	 * 修改二级密码
	 * @return array|mixed
	 */
	function updateuser2passwd()
	{
		if(request()->isPost()){
			$data=input('post.');
			//var_dump($data);
			$r=osc_service('common','Member')->updateuser2passwd($data);
			if(isset($r['error'])){
				return $r;
			}	
			return array('success'=>'修改二级密码成功','url'=>'/mobile');

		}
		$this->assign('top_title','修改二级密码');
		$this->assign('userinfo',Db::name('member')->where('uid',UID)->find());		
		$this->assign('SEO',['title'=>'修改二级密码-'.config('SITE_TITLE')]);
		
		$this->assign('flag','user');
		
		return $this->fetch();

	}

	/**
	 * 实名认证
	 * @return array|mixed
	 */
	function updateidcard()
	{
		$info=null;
       	if(request()->isPost()){
			$data=input('post.');
			//var_dump($data);
			$r=osc_service('common','Member')->updateidcard($data);
			if(isset($r['error'])){
				return $r;
			}	
			return array('success'=>'提交实名认证信息成功','url'=>'/mobile');

		}
		if(request()->isGet())
		{
			$data=input('param.');
			if($data){
				if($data['id']==1)
				{
					$info="您还没有做实名认证，请先做实名认证处理";
				}
			}

			
		}
		$username = session("username");
        $user=Db::name('member')->where('username',$username)->find();
        if($user['isauth']!=0)
        {
        	$this->redirect(url('/mobile/user/userindex'));	
        }




       	$this->assign('top_title','实名认证');
		$this->assign('userinfo',Db::name('member')->where('uid',UID)->find());		
		$this->assign('SEO',['title'=>'实名认证'.config('SITE_TITLE')]);
		
		$this->assign('flag','user');
		$this->assign('info',$info);
		
		return $this->fetch();

	}

	/**
	 * 绑定银行信息
	 * @return array|mixed
	 */
	function updatebank()
	{
		if(request()->isPost()){
			$data=input('post.');
			//var_dump($data);
			$r=osc_service('common','Member')->updatebank($data);
			if(isset($r['error'])){
				return $r;
			}	
			return array('success'=>'提交银行信息成功','url'=>'/mobile');

		}
		$username = session("username");
		$bank = Db::name('user_bank')->where('username',$username)->find();
       	$this->assign('bank',$bank);
       	$this->assign('top_title','更新银行卡信息');
		$this->assign('userinfo',Db::name('member')->where('uid',UID)->find());		
		$this->assign('SEO',['title'=>'更新银行卡信息'.config('SITE_TITLE')]);
		
		$this->assign('flag','user');
		
		return $this->fetch();

	}

	public function updatearear()
	{
       	$this->assign('top_title','更新用户归属信息');
	
		$this->assign('SEO',['title'=>'更新用户归属信息'.config('SITE_TITLE')]);
		return $this->fetch();		
	}

	public function send2bank()
	{
		//$data=input('post.');	
		//var_dump($data);
		//$data['mobile']  = $data['from_user'] = $mobile = trim(input('post.username', null));
		//echo $data['mobile'];
		//echo "infosys";
		//$this->sendsms($data['mobile']);
		$mobile = session("username");
		
		$ret = "0";
		if($mobile)
		{
           $r=osc_service('common','Member')->sendsms_common($mobile,'updatebank');

		}

		//retrun $ret;
	}

	function userindex()
	{

		$username = session('username');
        $userinfo = Db::name('member')->where('username',$username)->find();
        $bank = Db::name('user_bank')->where('username',$username)->find();
        
        if(!$bank)
        {
        	$bank['bankname']='未设置';
        	$bank['bankaccountname']='未设置';
        	$bank['subbankname']='未设置';
        	$bank['bankaccount']='未设置';

        }
        $prv = Db::name('area')->where('area_id',$userinfo['province_id'])->find();
        $city = Db::name('area')->where('area_id',$userinfo['city_id'])->find();
        $country = Db::name('area')->where('area_id',$userinfo['country_id'])->find();

        $area = $prv['area_name'].' '.$city['area_name'].' '.$country['area_name'];


        if($userinfo['isauth']==0)
        {
        	$userinfo['idcardname'] = '未实名认证';
        	$userinfo['idcard'] = '未实名认证';
        }
		$this->assign('top_title','个人信息面板');
		$this->assign('userinfo',$userinfo);	
		$this->assign('bank',$bank);	
		$this->assign('area',$area);	
		$this->assign('SEO',['title'=>'个人信息面板-'.config('SITE_TITLE')]);
		
		$this->assign('flag','user');
		
		return $this->fetch();
	}

	function exchange_trade(){
		$user = session('username');
		$house = Db::name('exchange_house')->where(['state'=>1])->field('id,name')->select();

		foreach($house as &$value){
			$map = [
				'username' => $user,
				'exchange_id'	=> $value['id']
			];
			$value['status'] = DB::name('exchange_trade_acc')->where($map)->count();
		}
		$this->assign('house',$house);
		$this->assign('top_title','交易所帐号管理');
		return $this->fetch();
	}

	function updatetrade(){
		$id = input('param.id/d');
		$uid = session('username');
		$user = Db::name('member')->where(['username'=> $uid])->find();
		$user['idcard'] = substr_replace($user['idcard'],"***********",3,11);
		$trade_acc = Db::name('exchange_trade_acc')->where(['exchange_id'=>$id,'username'=>$uid])->find();
		$trade = Db::name('exchange_house')->where(['id'=>$id])->find();
		$this->assign('trade_acc',$trade_acc);
		$this->assign('trade',$trade);
		$this->assign('user',$user);
		$this->assign('top_title','交易所帐号绑定');
		return $this->fetch();
	}

	/**
	 * 绑定交易所信息
	 * @return array
	 * @throws \think\Exception
	 */
	function tradeadd(){
		$data = input('post.');
		if($data['trade_id'] == ''){
			return array('error'=>'主账号不能为空');
		}
		if($data['trade_id'] != $data['trade_id_ss']){
			return array('error'=>'两次主账号不一致');
		}
		$map = [
			'exchange_id'=>$data["exchange_id"],
			'username'=>$data['username']
		];
		$trade_acc = Db::name('exchange_trade_acc')->where($map)->find();

		if(empty($trade_acc)){
			$info = [
				'username' => $data['username'],
				'exchange_id'=>$data["exchange_id"],
				'trade_id'	=> $data['trade_id'],
				'sub_trade_id'	=> $data['sub_trade_id'],
			];
			$res = Db::name('exchange_trade_acc')->insert($info);
			if($res){
				return array('success'=>'交易所帐号绑定成功','url'=>'/exchange_trade');
			}else{
				return array('error'=>'交易所帐号绑定失败');
			}
		}else{
			$info = [
					'trade_id' => $data['trade_id'],
					'sub_trade_id'	=> $data['sub_trade_id'],
			];
			$res = Db::name('exchange_trade_acc')->where($map)->update($info);
			if($res){
				return array('success'=>'交易所帐号修改成功','url'=>'/exchange_trade');
			}else{
				return array('error'=>'交易所帐号修改失败');
			}
		}
	}
	
	public function doUpload(){
		$files = request()->file('image');
//		echo"<pre>";print_r(ROOT_PATH);exit;
		if($files){
			$info="";
			foreach($files as $picFile){

				// 移动到框架应用根目录/public/uploads/ 目录下
				$info = $picFile->move(ROOT_PATH.'/public/uploads'.DS.'images');


				/*获取存储路径，以便插入数据库*/
				/* $path= "/uploads/images/".$info->getSaveName();*/

			}
			if($info!==""){
				$this->success($info);
				// 成功上传后 获取上传信息
				// 输出 jpg
				/* echo $info->getExtension();*/
				// 输出 42a79759f284b767dfcb2a0197904287.jpg
				/*echo $info->getFilename();*/
			}else{
				// 上传失败获取错误信息
				/* echo $file->getError();*/
				$this->error('上传失败！');
			}
		}
	}
}
